/**
 * 数据相关逻辑处理
 */
import { $reqAll, $get, $postJson } from 'ts-element/packages/utils/ajax'
import store from '../store';
export async function reqDsUrl(curObj, show, reqParamStr = {}, reqParams = []) {
    if (!curObj.reqUrl) {
        return
    }
    let param = {}
    if (curObj.conditionDefine && curObj.conditionDefine.length > 0) {
        for (let item of curObj.conditionDefine) {
            try {
                item.value = doValueByType(item.type, item.value)
            } catch (error) { }
            param[item.name] = item.value
        }
    }
    for (let item of reqParams) {
        param[item.name] = item.value
    }
    curObj = doServerIPReqUrl({ dsConfig: curObj })
    param = Object.assign(param, reqParamStr)
    // 获取字段内容curObj
    return (await $reqAll(curObj.reqUrl, param, show, curObj.reqType, curObj.contentType)) || {}
}

function doValueByType(type, value) {
    switch (type) {
        case 'Boolean':
            return Boolean(value)
        case 'Number':
            return Number(value)
        default:
            return value
    }
}
// 通过返回节点获取json中的对象
export function getJsonObjByResNode(res, resNode) {
    if (resNode) {
        // 取节点
        for (let node of resNode.split('.')) {
            res = res[node]
        }
    } else {
        res = res.rows || res.object || []
    }
    if (Array.isArray(res)) {
        res = res[0]
    }
    return res
}
/**
 * 处理参数尾置
 * @param {*} paramData 
 * @param {*} url 
 */
export function doReqParamEnd(paramData = {}, url) {
    if (paramData.$$reqParamEnd) { // 参数尾置
        url = (url.indexOf('/') == url.length - 1 ? url : url + '/') + paramData.$$reqParamEnd
        delete paramData.$$reqParamEnd
    }
    return url
}
/**
 * 清空表单项
 * @param {*} _this 
 * @param {*} formRef 
 */
export function clearFormData(_this, formRef) {
    formRef.clearValidate()
    let formDom = formRef.$attrs.element
    formDom.attr.data = {}
    setFormtemParam(
        formDom.componentData,
        _this.pageData['$form' + formDom.id],
        true
    )
}
/**
 * 给表单内所有的控件增加数据源ID
 * @param {}} componentData 
 * @param {*} dsId 
 */
export function setDsIdByFormComponent(componentData, dsId) {
    for (let lay of componentData) {
        if (lay.component == 'biTabs') {
            for (let tab of lay.tabs) {
                setDsIdByFormComponent(tab.componentData, array)

            }
        } else if (lay.isPanel) {
            setDsIdByFormComponent(lay.componentData, array)
        }
        if (Object.keys(lay.attr).indexOf('dsId') > -1) {
            lay.attr.dsId = dsId
        }
    }
}

/**
 * 根据字符串获取数据对象的元素 如'aa.cc.dd',默认用formID做为对象
 * @param {} item 
 */
export function varFormObj({ isEdit, item, pageData }) {
    let key = '$form' + item.id
    //给form设置一个全局和虚拟的form提交对象，仅用于表单数据回显和提交
    pageData[key] = {}
    pageData[key] = getFromItemParam(item.componentData, pageData[key])
    return pageData[key]
}

/**
 * 或许对象最后一个元素
 * @param {*} dsParam 
 */
export function getDsParam(dsParam) {
    let array = dsParam.split('.')
    if (array.length == 1) {
        return dsParam
    } else {
        return array[array.length - 1]
    }
}
/**
 * 根据组件项初始化规则
 * @param {组件} item 
 */
export function getRules(item) {
    let rules = []
    if (item.attr.emphasize) { // 必填
        rules.push({ required: true, message: item.attr.rulesMsg || (item.attr.title + '不能为空'), trigger: 'blur' })
    }
    for (let rule_ of item.attr.formRules) {
        if (rule_.type == 1 && rule_.pattern) { // 正则表达式
            rules.push({ pattern: rule_.pattern, message: rule_.message })
        } else if (rule_.ruleFun) { // 函数
            rule_.ruleFun = getPageDataByReplace(rule_.ruleFun, 'this')
            rules.push({
                validator: eval(rule_.ruleFun),
                trigger: 'blur'
            })
        }
    }
    return rules
}
// 获取全局变量
export function getPageDataByReplace(str, _thisStr) { // 还需处理方法上下文???
    return str.split('globalState').join(_thisStr + '.pageData').split('resState').join('resData')
}


// 获取全局变量
export async function saveDSEvent(dsComponent, _this) { // 还需处理方法上下文???
    let data = {
        apiType: dsComponent.type,
        categoryCode: dsComponent.categoryCode,
        categoryName: dsComponent.categoryName,
        label: dsComponent.label,
        productId: _this.$store.state.productId,
        reqType: dsComponent.reqType,
        reqUrl: dsComponent.reqUrl,
        rowsNode: dsComponent.resNode,
        description: dsComponent.description,
        columnDefine: JSON.stringify(dsComponent.columnDefine),
        columnDefineStr: '',
        conditionDefine: JSON.stringify(dsComponent.conditionDefine),
        reqServeAddr: dsComponent.reqServeAddr
    }
    let url = '/ts-pdc/api/DesignerApiPool/save'
    if (dsComponent.type == 'APISERVICE') {
        data = { ...dsComponent, ...data }
        delete data.tableColumns
        url = '/ts-pdc/api/APIService/saveOrUpdate'
        data.reqType = 'post'
        data.rowsNode = 'rows'
    } else if (dsComponent.id) {
        data.id = dsComponent.id
        url = '/ts-pdc/api/DesignerApiPool/update'
    }
    data.categoryName = data.categoryCode
    let res = await $postJson(url, data, false)
    if (res.success) {
        _this.$message.success('保存成功')
        _this.$refs.AttrDsConfig.isShowEvent = false
        _this.refreshDsComponents(dsComponent.categoryCode,dsComponent.id)
    }
    // if (!dsComponent.cate) { // 默认是为其他
    //     dsComponent.cate = '其他'
    // }
    // if (!dsComponent.id) {
    //     // 新增
    //     dsComponent.id = _this.$utils.uuid(8)
    //     dsComponent.icon = 'icon-shujuku2'
    //     if (!_this.dsComponents[dsComponent.cate]) {
    //         _this.dsComponents[dsComponent.cate] = []
    //     }
    //     _this.dsComponents[dsComponent.cate].push(dsComponent)
    // } else {
    //     if (_this.$refs.AttrDsConfig.oldCate != dsComponent.cate) { // 更换了分类，需重新整理分类
    //         if (!_this.dsComponents[dsComponent.cate]) {
    //             _this.dsComponents[dsComponent.cate] = []
    //         }
    //         _this.dsComponents[dsComponent.cate].push(dsComponent) // 新增分类
    //         let index = _this.dsComponents[dsComponent.oldCate].findIndex(res => res.id == dsComponent.id)
    //         _this.dsComponents[dsComponent.oldCate].splice(index, 1) //删除冗余分类
    //     } else { // 修改
    //         _this.dsComponents[dsComponent.cate][_this.$refs.AttrDsConfig.i] = dsComponent
    //     }
    // }
    // _this.$refs.AttrDsConfig.isShowEvent = false // 隐藏弹窗
    // refreshDsSet(_this)
}
// /**
//  * 刷新数据集
//  * @param {} _this 
//  */
// function refreshDsSet(_this) {
//     _this.tabItems[4].props.key = _this.$utils.uuid(8) //刷新dom节点
//     _this.$forceUpdate()
// }
// 删除数据源
export async function delDSEvent({ item, i, key }, _this) {
    _this.$mModal
        .confirm(`是否确定要删除【${item.label}】吗？`)
        .then(async type => {
            if (type === 'confirm') {
                let res = await $get(
                    '/ts-pdc/api/DesignerApiPool/delete/' + item.id
                )
                if (res.success) {
                    _this.$message.success('删除成功')
                    _this.refreshDsComponents(item.categoryCode)
                } else {
                    _this.$message.error(res.message || '删除失败，请联系管理员')
                }
            }
        })


}

/**
 * 递归嵌套找到，找到距离最近的表单Dom
 * @param {} param0 
 * @param {*} _this 
 */
export function getFormDom(layoutDom) {
    if (layoutDom && layoutDom.$attrs.element && layoutDom.$attrs.element.component == 'el-form') { // 递归嵌套找到，找到最近的formDom
        return layoutDom
    } else {
        let dom = layoutDom ? getFormDom(layoutDom.$parent) : null
        if (dom) {
            return dom
        }
    }
    return null
}
/**
 * 处理第三方url内容
 * @param {*} param0 
 */
export function doServerIPReqUrl({ dsConfig }) {
    dsConfig = _.cloneDeep(dsConfig)
    if (dsConfig.reqServeAddr && store.state.serverIPDatas && dsConfig.reqUrl && store.state.serverIPDatas.length > 0) {// 第三方服务有值
        let serverObj = store.state.serverIPDatas.find(res => res.itemName == dsConfig.reqServeAddr)
        if (serverObj && serverObj.itemCode && dsConfig.reqUrl.indexOf(serverObj.itemCode) != 0) {// 值不为空
            dsConfig.reqUrl = serverObj.itemCode + (serverObj.itemCode.substr(serverObj.itemCode.length - 2, serverObj.itemCode.length - 1) != '/' && dsConfig.reqUrl.substr(0, 1) != '/' ? '/' : '') + dsConfig.reqUrl
        }
    }
    if (dsConfig.reqType && dsConfig.reqType.indexOf('/') > -1) {// 带有contentType
        dsConfig.reqType = dsConfig.reqType.split('/')[0]
        dsConfig.contentType = 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    return dsConfig
}
/**
 * 通过组件内的数据源id找到postData和数据源对象
 */
export function getPostDataByDsId({ _this, dataSourceId, item }) {
    let dsConfig = _.cloneDeep(_this.$store.state.dataSourceData.find(res => res.id == dataSourceId) || {})
    let postData = {}
    if (dsConfig && dsConfig.conditionDefine && dsConfig.conditionDefine.length > 0) { // 参数
        for (let con of dsConfig.conditionDefine) {
            if (con.name) {
                postData[con.name] = postData[con.name] || doValueByType(con.type, con.value) // 优先于自定义赋值
            }
        }
    }
    dsConfig = doServerIPReqUrl({ dsConfig })
    postData = getControlPostParams({ item, postData }) //获取控件独有的参数
    return { postData, dsConfig }

}
/**
 * 获取控件独有的参数
 * @param {*} param0 
 */
export function getControlPostParams({ item, postData = {} }) {
    if (item && item.attr && item.attr.dataItemJsonUrlParams) { // 控件单独的入参设置
        for (let param of item.attr.dataItemJsonUrlParams) {
            postData[param.paramName] = param.paramVal
        }
    }
    return postData
}

/**
 * 改变数据源
 * @param {*} dsComponent 
 */
export async function changeDataSource(dsComponent) {
    let dataSource = {}
    if (dsComponent.comType == 'dsModule') { // 数据模型
        if (!dsComponent.queryColumnList && !dsComponent.columnList) {// 未存在字段和参数，需按需加载
            let modelInfo = await getColumnInfoByModelId(dsComponent.id || dsComponent.modelId)
            if (Object.keys(modelInfo).length == 0) {
                return null
            }
            dsComponent.queryColumnList = modelInfo.queryColumnList
            dsComponent.columnList = modelInfo.columnList
        }
        dataSource = {
            id: dsComponent.id || dsComponent.modelId,
            label: (dsComponent.tableChName + `[${dsComponent.tableName}]`).toUpperCase(),
            categoryName: dsComponent.businessSecondName,
            conditionDefine: dsComponent.queryColumnList.map(res => { return { alias: res.datametaIdeName, name: res.columnName, value: '', format: res.format } }),
            columnDefine: dsComponent.columnList.map(res => { return { alias: res.datametaIdeName, name: res.columnName, value: '', format: res.format } }),
        }
    } else {
        dataSource = {
            reqType: dsComponent.reqType,
            reqUrl: dsComponent.reqUrl,
            rowsNode: dsComponent.rowsNode,
            reqServeAddr: dsComponent.reqServeAddr,
            id: dsComponent.id,
            label: dsComponent.label,
            categoryName: dsComponent.categoryName,
            columnDefine: JSON.parse(dsComponent.columnDefine || '[]'),
            conditionDefine: JSON.parse(
                dsComponent.conditionDefine || '[]'
            )
        }
    }
    dataSource.comType = dsComponent.comType
    return { ...dataSource }
}

/**
 * 根据模型获取字段信息
 */
export async function getColumnInfoByModelId(modelId) {
    let res = await $get(
        '/ts-dw/api/model/' + modelId
    )
    return res.object || {}
}
/**
 * 获取数据池
 */
export async function getAjaxDsDatas(apiType) {
    // let res = await $get(
    //     '/ts-pdc/api/DesignerApiPool/mapList', { productId: store.state.productId || 'unknow' }
    // )
    let res = await $get(
        '/ts-pdc/api/DesignerApiPool/mapList', { apiType: apiType }, true
    )
    // store.commit('design/setData', {
    //     label: 'dsComponents',
    //     value: res.object || res.rows || []
    // })
    return res.object || res.rows || []
}
/**
 * 获取数据模型池
 */
export async function getAjaxDsModuleDatas(store, _this) {
    let res = await $get(
        '/ts-dw/api/model/reportCateTreeWithModel', { includeColumn: 0 }, true
    )
    // let res = await $get(
    //     '/ts-data-report/api/DwReport/mapList'
    // )
    let data = res.object || res.rows || []
    // if (data.length > 0) {
    //     data[0].showList = true
    //     // data[0].listData = await getAjaxDsModuleDatasByType(data[0].sn)
    // }
    store.commit('setData', {
        label: 'dsModuleComponents',
        value: data
    })
}
/**
 * 获取数据模型池 通过tree类别
 */
export async function getAjaxDsModuleDatasByType(sn) {
    let res = await $get(
        '/ts-dw/api/model',
        { pageNo: 1, pageSize: 999, syncPublish: 1, businessTopicCateSn: sn }
    )
    return (res.object || {}).records || []
}

/**
 * 获取数据池
 */
export async function getAjaxApiPoolDetail(id) {
    let res = await $get(
        '/ts-pdc/api/DesignerApiPool/detail/' + id
    )
    return res.object
}

/**
 * 获取SQL数据池
 */
export async function getSQLPoolDetail(id) {
    let res = await $get(
        '/ts-pdc/api/APIService/' + id
    )
    return res.object
}

/**
 * 设置数据源id内容
 * @param {*} param0 
 */
export async function setDataSourceIdToPage({ dataSourceId }) {
    let index = store.state.dataSourceData.findIndex(res => res.id == dataSourceId)
    if (index == -1) {//不存在，则需手动加入
        let dataSource = await getAjaxApiPoolDetail(dataSourceId)
        if (dataSource && dataSource.id) {// 数据池
            dataSource.comType = 'ds'
        } else {
            dataSource = { comType: 'dsModule', id: dataSourceId }
        }
        dataSource = await changeDataSource(dataSource)
        if (dataSource) {
            store.commit('addDataSourceData', { dataSource })
        }
    }
}
